package cn.ncu.wechat.util;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class wechatConfigUtil {

    public static String getAccessToken(String appId, String appSecret) {
        String urlString = String.format(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                appId, appSecret);

        StringBuilder response = new StringBuilder();

        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 使用 Gson 解析 JSON
                JsonObject jsonObject = JsonParser.parseString(response.toString()).getAsJsonObject();

                // 直接通过键名获取 access_token
                if (jsonObject.has("access_token")) {
                    return jsonObject.get("access_token").getAsString();
                } else {
                    System.out.println("Failed to get access_token. Response: " + response);
                    return null;
                }
            } else {
                System.out.println("GET request failed. Response Code: " + responseCode);
                return null;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }
}